package com.hhu.wangzb.common.entity.index;

import com.hhu.wangzb.common.entity.BoxChangeEntity;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 实体索引树，存储数据库中表项间外键关系
 */
public class EntityIndexTree {

    private List<IndexNode> treeNodes = new ArrayList<>();

    private static class IndexNode {

        Integer id;
        Integer parentId;
        List<Integer> childrenIds;
        Class<?> entityClass;

        public IndexNode() {
            this.id = -1;
            this. parentId = -1;
            this.childrenIds = new ArrayList<>();
            this.entityClass = null;
        }

        @Override
        public String toString() {
            return "IndexNode{" +
                    "id=" + id +
                    ", parentId=" + parentId +
                    ", childrenIds=" + childrenIds +
                    ", entityClass=" + entityClass +
                    '}';
        }
    }

    public void addNode(IndexNode node) {
        this.treeNodes.add(node);
    }

    public void addNode(Class<?> entityClass, Integer id, Integer parentId, Integer... childrenIds) {
        IndexNode node = new IndexNode();
        node.entityClass = entityClass;
        node.id = id;
        node.parentId = parentId;
        node.childrenIds.addAll(Arrays.asList(childrenIds));

        addNode(node);
    }

    public IndexNode getNode(Integer id) {
        for (IndexNode node : treeNodes) {
            if (node.id.equals(id)) return node;
        }
        return null;
    }

    public IndexNode getNode(Class<?> entityClass) {
        for (IndexNode node : treeNodes) {
            if (node.entityClass == entityClass) return node;
        }
        return null;
    }

    public IndexNode getRoot() {
        return getNode(-1);
    }

    public static void main(String[] args) {
        EntityIndexTree tree = new EntityIndexTree();

        tree.addNode(BoxChangeEntity.class, 1, -1, 2, 3, 4);

        IndexNode node1 = tree.getNode(BoxChangeEntity.class);
        System.out.println(node1);
    }
}
